import socket
import threading


class Client(threading.Thread):
    ip = socket.gethostbyname(socket.gethostname())
    port = 9999
    def __init__(self):
        threading.Thread.__init__(self)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def connect(self):
        self.s.connect((self.ip, self.port))
    def sendCientMessage(self, data):
        try:
            self.s.send(data.encode("utf-8"))
        except:
            print("The serrver exits.")
            self.s.close()
    def receiveServerMessage(self):
        try:
            msg = self.s.recv(1024)
        except:
            print("The server exits.")
            self.s.close()
            raise Exception("The server exits.")
        else:
            print("[server] >>> {0}".format(msg.decode("utf-8")))
            print(">>> ")
    def run(self):
        self.connect()
        while True:
            self.receiveServerMessage()

client = Client()
client.start()
while True:
    print(">>> ")
    data = input()
    #  todo 读取用户列表，遍历用户推送消息
    client.sendCientMessage(data)




